<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, viewport-fit=cover"/>
<meta name="description" content="TypeScript: Allow the user to shift the label of a node."/> 
<link rel="stylesheet" href="../assets/css/style.css"/> 
<!-- Copyright 1998-2021 by Northwoods Software Corporation. -->
<title>State Chart with Draggable Node Labels</title>
</head>

<body>
  <!-- This top nav is not part of the sample code -->
  <nav id="navTop" class="w-full z-30 top-0 text-white bg-nwoods-primary">
    <div class="w-full container max-w-screen-lg mx-auto flex flex-wrap sm:flex-nowrap items-center justify-between mt-0 py-2">
      <div class="md:pl-4">
        <a class="text-white hover:text-white no-underline hover:no-underline
        font-bold text-2xl lg:text-4xl rounded-lg hover:bg-nwoods-secondary " href="../">
          <h1 class="mb-0 p-1 ">GoJS</h1>
        </a>
      </div>
      <button id="topnavButton" class="rounded-lg sm:hidden focus:outline-none focus:ring" aria-label="Navigation">
        <svg fill="currentColor" viewBox="0 0 20 20" class="w-6 h-6">
          <path id="topnavOpen" fill-rule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM9 15a1 1 0 011-1h6a1 1 0 110 2h-6a1 1 0 01-1-1z" clip-rule="evenodd"></path>
          <path id="topnavClosed" class="hidden" fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
        </svg>
      </button>
      <div id="topnavList" class="hidden lg:text-base sm:block items-center w-auto mt-0 text-white p-0 z-20">
        <ul class="list-reset list-none font-semibold flex justify-end flex-wrap sm:flex-nowrap items-center px-0 pb-0">
          <li class="p-1 sm:p-0"><a class="topnav-link" href="../learn/">Learn</a></li>
          <li class="p-1 sm:p-0"><a class="topnav-link" href="../samples/">Samples</a></li>
          <li class="p-1 sm:p-0"><a class="topnav-link" href="../intro/">Intro</a></li>
          <li class="p-1 sm:p-0"><a class="topnav-link" href="../api/">API</a></li>
          <li class="p-1 sm:p-0"><a class="topnav-link" href="https://www.nwoods.com/products/register.html">Register</a></li>
          <li class="p-1 sm:p-0"><a class="topnav-link" href="../download.html">Download</a></li>
          <li class="p-1 sm:p-0"><a class="topnav-link" href="https://forum.nwoods.com/c/gojs/11">Forum</a></li>
          <li class="p-1 sm:p-0"><a class="topnav-link" href="https://www.nwoods.com/contact.html"
           target="_blank" rel="noopener" onclick="getOutboundLink('https://www.nwoods.com/contact.html', 'contact');">Contact</a></li>
          <li class="p-1 sm:p-0"><a class="topnav-link" href="https://www.nwoods.com/sales/index.html"
           target="_blank" rel="noopener" onclick="getOutboundLink('https://www.nwoods.com/sales/index.html', 'buy');">Buy</a></li>
        </ul>
      </div>
    </div>
    <hr class="border-b border-gray-600 opacity-50 my-0 py-0" />
  </nav>
  <div class="md:flex flex-col md:flex-row md:min-h-screen w-full max-w-screen-xl mx-auto">
    <div id="navSide" class="flex flex-col w-full md:w-48 text-gray-700 bg-white flex-shrink-0"></div>
    <!-- * * * * * * * * * * * * * -->
    <!-- Start of GoJS sample code -->
    

    <div class="p-4 w-full">
  <div id="sample">
    <div id="myDiagramDiv" style="background-color: whitesmoke; border: solid 1px black; width: 100%; height: 400px"></div>
    <p>
      This sample is a modification of the <a href="../samples/stateChart.html">State Chart</a> sample
      that makes use of the NodeLabelDraggingTool that is defined in its own file, as <a href="NodeLabelDraggingTool.ts">NodeLabelDraggingTool.ts</a>.
    </p>
    <p>
      Note that after dragging a node label you can move that node and the label maintains the same position relative to the node.
      That relative position is specified by the <a>GraphObject.alignment</a> property, used by the "Spot" <a>Panel</a>.
      This sample also saves any changes to that property by means of a TwoWay <a>Binding</a>.
    </p>
    <button id="SaveButton">Save</button>
    <button id="LoadButton">Load</button> Diagram Model saved in JSON format:
    <br />
    <textarea id="mySavedModel" style="width:100%;height:300px">
{ "nodeKeyProperty": "id",
  "nodeDataArray": [
    { "id": 0, "loc": "120 120", "text": "Initial" },
    { "id": 1, "loc": "330 120", "text": "First down" },
    { "id": 2, "loc": "226 376", "text": "First up" },
    { "id": 3, "loc": "60 276", "text": "Second down" },
    { "id": 4, "loc": "226 226", "text": "Wait" }
  ],
  "linkDataArray": [
    { "from": 0, "to": 0, "text": "up or timer", "curviness": -20 },
    { "from": 0, "to": 1, "text": "down", "curviness": 20 },
    { "from": 1, "to": 0, "text": "up (moved)\nPOST", "curviness": 20 },
    { "from": 1, "to": 1, "text": "down", "curviness": -20 },
    { "from": 1, "to": 2, "text": "up (no move)" },
    { "from": 1, "to": 4, "text": "timer" },
    { "from": 2, "to": 0, "text": "timer\nPOST" },
    { "from": 2, "to": 3, "text": "down" },
    { "from": 3, "to": 0, "text": "up\nPOST\n(dblclick\nif no move)" },
    { "from": 3, "to": 3, "text": "down or timer", "curviness": 20 },
    { "from": 4, "to": 0, "text": "up\nPOST" },
    { "from": 4, "to": 4, "text": "down" }
  ]
}
    </textarea>
  </div>

  <script type="module" id="code">
    import * as go from "../release/go-module.js";
    import { NodeLabelDraggingTool } from './NodeLabelDraggingTool.js';

    if (window.goSamples) window.goSamples(); // init for these samples -- you don't need to call this
    const $ = go.GraphObject.make; // for conciseness in defining templates

    const myDiagram =
        $(go.Diagram, 'myDiagramDiv', // must name or refer to the DIV HTML element
        {
            // have mouse wheel events zoom in and out instead of scroll up and down
            'toolManager.mouseWheelBehavior': go.ToolManager.WheelZoom,
            // support double-click in background creating a new node
            'clickCreatingTool.archetypeNodeData': { text: 'new node' },
            // enable undo & redo
            'undoManager.isEnabled': true
        });
    // install the NodeLabelDraggingTool as a "mouse move" tool
    myDiagram.toolManager.mouseMoveTools.insertAt(0, new NodeLabelDraggingTool());

    // when the document is modified, add a "*" to the title and enable the "Save" button
    myDiagram.addDiagramListener('Modified', (e) => {
        const button = document.getElementById('SaveButton');
        if (button)
            button.disabled = !myDiagram.isModified;
        const idx = document.title.indexOf('*');
        if (myDiagram.isModified) {
            if (idx < 0)
                document.title += '*';
        }
        else {
            if (idx >= 0)
                document.title = document.title.substr(0, idx);
        }
    });

    // define the Node template
    myDiagram.nodeTemplate =
        $(go.Node, 'Spot', { locationObjectName: 'ICON', locationSpot: go.Spot.Center }, new go.Binding('location', 'loc', go.Point.parse).makeTwoWay(go.Point.stringify), { selectionObjectName: 'ICON' },
        // define the node primary shape
        $(go.Shape, 'RoundedRectangle', {
            name: 'ICON',
            parameter1: 10,
            desiredSize: new go.Size(40, 40),
            fill: $(go.Brush, 'Linear', { 0: 'rgb(254, 201, 0)', 1: 'rgb(254, 162, 0)' }),
            stroke: 'black',
            portId: '',
            fromLinkable: true,
            fromLinkableSelfNode: true,
            fromLinkableDuplicates: true,
            toLinkable: true,
            toLinkableSelfNode: true,
            toLinkableDuplicates: true,
            cursor: 'pointer'
        }), $(go.Shape, // provide interior area where the user can grab the node
        { fill: 'transparent', stroke: null, desiredSize: new go.Size(30, 30) }), $(go.TextBlock, {
            font: 'bold 11pt helvetica, bold arial, sans-serif',
            editable: true,
            _isNodeLabel: true,
            cursor: 'move' // visual hint that the user can do something with this node label
        }, new go.Binding('text', 'text').makeTwoWay(),
        // The GraphObject.alignment property is what the NodeLabelDraggingTool modifies.
        // This TwoWay binding saves any changes to the same named property on the node data.
        new go.Binding('alignment', 'alignment', go.Spot.parse).makeTwoWay(go.Spot.stringify)));
    // unlike the normal selection Adornment, this one includes a Button
    myDiagram.nodeTemplate.selectionAdornmentTemplate =
        $(go.Adornment, 'Spot', $(go.Panel, 'Auto', $(go.Shape, { fill: null, stroke: 'blue', strokeWidth: 2 }), $(go.Placeholder) // this represents the selected Node
        ),
        // the button to create a "next" node, at the top-right corner
        $('Button', {
            alignment: go.Spot.TopRight,
            click: addNodeAndLink // this function is defined below
        }, $(go.Shape, 'PlusLine', { desiredSize: new go.Size(6, 6) })) // end button
        ); // end Adornment
    // clicking the button inserts a new node to the right of the selected node,
    // and adds a link to that new node
    function addNodeAndLink(e, obj) {
        const adorn = obj.part;
        const fromNode = adorn.adornedPart;
        if (fromNode === null)
            return;
        e.handled = true;
        const diagram = e.diagram;
        diagram.startTransaction('Add State');
        // get the node data for which the user clicked the button
        const fromData = fromNode.data;
        // create a new "State" data object, positioned off to the right of the adorned Node
        const toData = { text: 'new' };
        const p = fromNode.location.copy();
        p.x += 200;
        toData.loc = go.Point.stringify(p); // the "loc" property is a string, not a Point object
        // add the new node data to the model
        const model = diagram.model;
        model.addNodeData(toData);
        // create a link data from the old node data to the new node data
        const linkdata = {
            from: model.getKeyForNodeData(fromData),
            to: model.getKeyForNodeData(toData),
            text: 'transition'
        };
        // and add the link data to the model
        model.addLinkData(linkdata);
        // select the new Node
        const newnode = diagram.findNodeForData(toData);
        diagram.select(newnode);
        diagram.commitTransaction('Add State');
        // if the new node is off-screen, scroll the diagram to show the new node
        if (newnode !== null)
            diagram.scrollToRect(newnode.actualBounds);
    }
    // replace the default Link template in the linkTemplateMap
    myDiagram.linkTemplate =
        $(go.Link, // the whole link panel
        { curve: go.Link.Bezier, adjusting: go.Link.Stretch, reshapable: true }, new go.Binding('points').makeTwoWay(), new go.Binding('curviness', 'curviness'), $(go.Shape, // the link shape
        { strokeWidth: 1.5 }), $(go.Shape, // the arrowhead
        { toArrow: 'standard', stroke: null }), $(go.Panel, 'Auto', $(go.Shape, // the label background, which becomes transparent around the edges
        {
            fill: $(go.Brush, 'Radial', { 0: 'rgb(240, 240, 240)', 0.3: 'rgb(240, 240, 240)', 1: 'rgba(240, 240, 240, 0)' }),
            stroke: null
        }), $(go.TextBlock, 'transition', // the label text
        {
            textAlign: 'center',
            font: '10pt helvetica, arial, sans-serif',
            stroke: 'black',
            margin: 4,
            editable: true // editing the text automatically updates the model data
        }, new go.Binding('text', 'text').makeTwoWay())));

    // read in the JSON-format data from the "mySavedModel" element
    load();

    // Show the diagram's model in JSON format
    function save() {
      document.getElementById('mySavedModel').value = myDiagram.model.toJson();
      myDiagram.isModified = false;
    }
    function load() {
      myDiagram.model = go.Model.fromJson(document.getElementById('mySavedModel').value);
    }
    document.getElementById("SaveButton").onclick = app.save;
    document.getElementById("LoadButton").onclick = app.load;

    window.myDiagram = myDiagram; // Attach to the window for console debugging
  </script>
    </div>
    <!-- * * * * * * * * * * * * * -->
    <!--  End of GoJS sample code  -->
  </div>
</body>
<!--  This script is part of the gojs.net website, and is not needed to run the sample -->
<script src="../assets/js/goSamples.js"></script>
</html>
